import { type MaybeRefOrGetter, onMounted, ref } from 'vue';

type ScrollElement = HTMLElement | Window;

const overflowScrollReg = /scroll|auto|overlay/i;
const defaultRoot = window;

function isElement(node: Element) {
  const ELEMENT_NODE_TYPE = 1;
  return (
    node.tagName !== 'HTML'
    && node.tagName !== 'BODY'
    && node.nodeType === ELEMENT_NODE_TYPE
  );
}

// https://github.com/vant-ui/vant/issues/3823
export function getScrollParent(
  el: Element,
  root: ScrollElement | undefined = defaultRoot,
) {
  let node = el;

  while (node && node !== root && isElement(node)) {
    const { overflowY } = window.getComputedStyle(node);
    if (overflowScrollReg.test(overflowY)) {
      return node;
    }
    node = node.parentNode as Element;
  }

  return root;
}

/**
 * 获取滚动父级元素
 * @param el 元素
 * @param root 根元素
 */
export function useScrollParent(
  el?: MaybeRefOrGetter<Element | undefined>,
  root: ScrollElement | undefined = defaultRoot,
) {
  const $el = toRef(el);
  const $ctxEl = ref<Element>();
  const scrollParent = ref<Element | Window>();

  onMounted(() => {
    if (!$el.value) {
      const ins = getCurrentInstance();
      $ctxEl.value = (ins as any)?.ctx?.$el.parentElement;
    }

    const $finalEl = $el.value || $ctxEl.value;

    if ($finalEl) {
      scrollParent.value = getScrollParent($finalEl, root);
    }
  });

  return scrollParent;
}
